"""
    手写数字预测
"""

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split # 划分数据集
from sklearn.preprocessing import MinMaxScaler
import joblib
from common.functions import sigmoid_function, softmax_function_v2


# 读取数据
def get_data():
    # 1. 读取数据集
    data = pd.read_csv("../data/train.csv")
    # 2. 划分数据集和测试集
    X = data.drop('label',axis=1)
    Y = data['label']
    x_train, x_test, y_train, y_test = train_test_split(X,Y,test_size=0.3,random_state=42)

    # 3. 归一化处理
    preprocessor = MinMaxScaler()
    x_train = preprocessor.fit_transform(x_train)
    x_test = preprocessor.fit_transform(x_test)

    return x_test,y_test

# 初始化神经网络(加载神经网络,从已经训练好的的参数中加载)
def init_network():
    network = joblib.load("../data/nn_sample")
    return network

def forward(network,x):
    """
        :param network: 网络
        :param x:       输入
        :return:        预测结果
        """

    W1,W2,W3 = network['W1'],network['W2'],network['W3']
    b1,b2,b3 = network['b1'],network['b2'],network['b3']

    a1 = np.dot(x,W1) + b1
    z1 = sigmoid_function(a1)

    a2 = np.dot(z1,W2) + b2
    z2 = sigmoid_function(a2)

    a3 = np.dot(z2,W3) + b3

    y = softmax_function_v2(a3)

    # 预测结果
    return y

# 主流程
if __name__ == '__main__':
    # 获取测试数据
    x,y =get_data()
    # 创建模型
    network = init_network()
    # 预测，得到分类概率
    y_probs = forward(network,x)
    # 根据概率得到分类标签
    y_pred = np.argmax(y_probs,axis=1)
    # 计算准确率
    n = x.shape[0]
    print(f"n is : {n},x shape is : {x.shape}")
    accuracy_cnt = np.sum(y == y_pred)
    print(f"accuracy is : {accuracy_cnt}")
    print("准确率是:",accuracy_cnt/n)



